var canvasWidth = Math.min( 800 , $(window).width() - 20 );//取最小值（800，和当前屏幕-20），适应pc和app
var canvasHeight = canvasWidth;

var strokeColor = "black";//当前绘制的颜色默认黑色
var isMouseDown = false;//是否按下鼠标
var lastLoc = {x:0,y:0};//记录上次绘制的位置，初始为 0 0
var lastTimestamp = 0;//记录最后的时间
var lastLineWidth = -1;//记录最后线条宽度 （根据速度）

var canvas = document.getElementById("canvas")
var context = canvas.getContext("2d")

canvas.width = canvasWidth
canvas.height = canvasHeight

$("#controller").css("width",canvasWidth+"px");//动态设置宽度值
drawGrid();
//点击清除
$("#clear_btn").click(
    function(e){
        context.clearRect( 0 , 0 , canvasWidth, canvasHeight );//清除canvas
        drawGrid();//绘制米字格
    }
)
//点击修改颜色
$(".color_btn").click(
    function(e){
        $(".color_btn").removeClass("color_btn_selected");//移除class值
        $(this).addClass("color_btn_selected");//添加class值
        strokeColor = $(this).css("background-color");//获取样式中的背景颜色属性值/颜色值
    }
)

//记录鼠标点击位置
function beginStroke(point){

    isMouseDown = true;//点击
    //console.log("mouse down!");
    lastLoc = windowToCanvas(point.x, point.y);//转换为canvas坐标
    lastTimestamp = new Date().getTime();//获取时间戳
}
function endStroke(){//修改变量
    isMouseDown = false
}

//写字
function moveStroke(point){

    var curLoc = windowToCanvas( point.x , point.y );//本次移动到的点
    var curTimestamp = new Date().getTime();//移动结束后时间戳
    var s = calcDistance( curLoc , lastLoc );//计算两点之间距离
    var t = curTimestamp - lastTimestamp;//用时

    var lineWidth = calcLineWidth( t , s );//根据计算的速度得出线条宽度

    //draw
    context.beginPath();
    context.moveTo( lastLoc.x , lastLoc.y );//lastLoc上次移动到的点
    context.lineTo( curLoc.x , curLoc.y );

    context.strokeStyle = strokeColor;//颜色
    context.lineWidth = lineWidth;//线条宽度
    context.lineCap = "round";//为绘制直线增加帽子，去毛边
    context.lineJoin = "round";//线条过度更衔接
    context.stroke();
//最后跟新时间和开始点以及线条宽度
    lastLoc = curLoc;
    lastTimestamp = curTimestamp;
    lastLineWidth = lineWidth;
}
//鼠标左键按下
canvas.onmousedown = function(e){
    e.preventDefault()//取消默认动作
    beginStroke( {x: e.clientX , y: e.clientY} );//记录位置
};
//鼠标左键离开
canvas.onmouseup = function(e){
    e.preventDefault()
    endStroke()//修改变量
};
//鼠标移除
canvas.onmouseout = function(e){
    e.preventDefault()
    endStroke()
};
//鼠标移动
canvas.onmousemove = function(e){
    e.preventDefault()
    if( isMouseDown ){//表示按下左键
        moveStroke({x: e.clientX , y: e.clientY});//绘制
    }
};

                    //手指触摸事件
canvas.addEventListener('touchstart',function(e){
    e.preventDefault()
    touch = e.touches[0];//表示取多点触控的第一个手指信息（包含x,y）
    beginStroke( {x: touch.pageX , y: touch.pageY} )
});
						//手指移动事件
canvas.addEventListener('touchmove',function(e){
    e.preventDefault()
    if( isMouseDown ){
        touch = e.touches[0]
        moveStroke({x: touch.pageX , y: touch.pageY})
    }
});
						//手指离开事件
canvas.addEventListener('touchend',function(e){
    e.preventDefault()
    endStroke()
});

var maxLineWidth = 30;//最大宽
var minLineWidth = 1;//最小宽
var maxStrokeV = 10;//最大速度
var minStrokeV = 0.1;//最小速度

//计算速度给出笔画线条宽度
function calcLineWidth( t , s ){

    var v = s / t;//速度

    var resultLineWidth;
    if( v <= minStrokeV )
        resultLineWidth = maxLineWidth;
    else if ( v >= maxStrokeV )
        resultLineWidth = minLineWidth;
    else{
        resultLineWidth = maxLineWidth - (v-minStrokeV)/(maxStrokeV-minStrokeV)*(maxLineWidth-minLineWidth);//计算中间值
    }

    if( lastLineWidth == -1 )
        return resultLineWidth;

    return resultLineWidth*1/3 + lastLineWidth*2/3;//取过度值过度一下（1  30  差距太大 ，根据上次和这次的比例分配 ）使得线条更平滑
}
//计算两点距离
function calcDistance( loc1 , loc2 ){

    return Math.sqrt( (loc1.x - loc2.x)*(loc1.x - loc2.x) + (loc1.y - loc2.y)*(loc1.y - loc2.y) )
}
//坐标系转换 从document到canvas
function windowToCanvas( x , y ){
    var bbox = canvas.getBoundingClientRect();//函数取得canvas的包围盒,包含canvas的各种信息
    return {x:Math.round(x-bbox.left) , y:Math.round(y-bbox.top)};//四舍五入取整
}

//画米字格图形
function drawGrid(){

    context.save()

    context.strokeStyle = "rgb(230,11,9)"//红色
	//边框
    context.beginPath()
    context.moveTo( 3 , 3 )
    context.lineTo( canvasWidth - 3 , 3 )
    context.lineTo( canvasWidth - 3 , canvasHeight - 3 )
    context.lineTo( 3 , canvasHeight - 3 )
    context.closePath()
    context.lineWidth = 6
    context.stroke()
	//米字格
    context.beginPath()
    context.moveTo(0,0)
    context.lineTo(canvasWidth,canvasHeight)

    context.moveTo(canvasWidth,0)
    context.lineTo(0,canvasHeight)

    context.moveTo(canvasWidth/2,0)
    context.lineTo(canvasWidth/2,canvasHeight)

    context.moveTo(0,canvasHeight/2)
    context.lineTo(canvasWidth,canvasHeight/2)

    context.lineWidth = 1
    context.stroke()

    context.restore()
}